import { throttle } from 'az-throttle'
import { debounce } from 'az-debounce'
import { checkModifier } from 'az-keyboard-modifier'

const delayFunc = {
  throttle,
  debounce,
}

export function f(cb, key, modifiers, delay, delayType, immediate, ...args) {
  const _cb = delayType === 'throttle' || delayType === 'debounce' ? delayFunc[delayType](cb, delay, !!immediate) : cb
  return modifiers
    ? function (e) {
        const event = e || window.event
        const keyCode = event.keyCode || event.which
        if (keyCode === key && checkModifier(event, modifiers)) {
          event.preventDefault ? event.preventDefault() : (event.returnValue = false)
          _cb.call(this, e, ...args)
        }
      }
    : function (e) {
        const event = e || window.event
        const keyCode = event.keyCode || event.which
        const tagName = event.target.tagName
        if (tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA') return
        if (keyCode === key && checkModifier(event, modifiers)) {
          event.preventDefault ? event.preventDefault() : (event.returnValue = false)
          _cb.call(this, e, ...args)
        }
      }
}

export function f_prevent(key, modifiers) {
  return modifiers
    ? function (e) {
        const event = e || window.event
        const keyCode = event.keyCode || event.which
        if (keyCode === key && checkModifier(event, modifiers)) {
          event.preventDefault ? event.preventDefault() : (event.returnValue = false)
        }
      }
    : function (e) {
        const event = e || window.event
        const keyCode = event.keyCode || event.which
        const tagName = event.target.tagName
        if (tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA') return
        if (keyCode === key && checkModifier(event, modifiers)) {
          event.preventDefault ? event.preventDefault() : (event.returnValue = false)
        }
      }
}
